package com.incar.chuxing.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.ocr.ui.camera.CameraView;
import com.baidu.ocr.ui.camera.ICameraControl;
import com.baidu.ocr.ui.camera.MaskView;
import com.bumptech.glide.Glide;
import com.incar.chuxing.R;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.UploadImageBaidu;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.utils.bos.UploadPicUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TakePictureActivity extends BaseActivity {
    @BindView(R.id.camera)
    CameraView cameraView;
    @BindView(R.id.textView_tip)
    TextView textView_tip;
    @BindView(R.id.take_photo_ok)
    TextView takePhotoOk;
    @BindView(R.id.sample_pic)
    ImageView samplePic;
    @BindView(R.id.iv_preview)
    ImageView ivPreview;
    @BindView(R.id.take_photo_button)
    ImageView takePhotoButton;
    @BindView(R.id.light_button)
    ImageView lightButton;
    @BindView(R.id.layout_sample)
    RelativeLayout layoutSample;

    private Context mContext = this;
    private File file;

    @Override
    public int getLayoutId() {
        return R.layout.activity_take_picture;
    }

    @Override
    public void initView() {
        cameraView.setCropType(CameraView.CROP_SQUARE);
        cameraView.setMaskType(MaskView.MASK_TYPE_NONE, mContext);
        takePhotoButton.setOnClickListener(v -> {
            checkperssionAndCamera();
        });


        textView_tip.setText(getIntent().getStringExtra("exampleStr"));
        if (!TextUtils.isEmpty(getIntent().getStringExtra("examplePicId"))) {
            layoutSample.setVisibility(View.VISIBLE);
            Glide.with(getApplicationContext()).load(getIntent().getStringExtra("examplePicId")).into(samplePic);
        } else {
            layoutSample.setVisibility(View.GONE);
        }
    }


    public void checkperssionAndCamera() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), 0);
            } else {
                takephoto();
            }
        } else {
            takephoto();
        }
    }


    private void takephoto() {
        takePhotoButton.setClickable(false);
        file = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + SDCardUtils.createReturnCarFileName(((MyApplication) getApplication()).getUid()) + ".jpg");
        cameraView.takePicture(file, takePictureCallback);
    }

    private CameraView.OnTakePictureCallback takePictureCallback = new CameraView.OnTakePictureCallback() {
        @Override
        public void onPictureTaken(final Bitmap bitmap) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    takePhotoButton.setClickable(true);
                    confirmPic(file);
                }
            });

        }
    };


    @Override
    protected void onResume() {
        cameraView.start();
        super.onResume();
    }

    @Override
    protected void onStop() {
        cameraView.stop();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (cameraView != null) {
            cameraView = null;
        }
        super.onDestroy();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    }


    private void confirmPic(File outputFile) {
        if (getIntent().getStringExtra("isConfirm").equals("0")) {
            ivPreview.setVisibility(View.GONE);
            preUploadImage(outputFile);
        } else {
            dismissLoadingDialog();
            ivPreview.setVisibility(View.VISIBLE);
            takePhotoOk.setVisibility(View.VISIBLE);
            takePhotoButton.setVisibility(View.INVISIBLE);
            Glide.with(mContext.getApplicationContext()).load(file).into(ivPreview);


        }
    }


    private String key;

    private void preUploadImage(final File picFile) {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        upLoadImage(response, picFile);
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void upLoadImage(Response<UploadImageBaidu> response, File picFile) {
        key = getFileNameNoEx(picFile);
        Logger.d("takePhoto", picFile.getAbsolutePath() + "");
        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                response.body().getAttachment().getStsToken(),
                response.body().getAttachment().getBucketName(),
                key, new UploadPicUtil.OnFinishListener() {
                    @Override
                    public void onSuccess() {
                        picFile.delete();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                                Intent intent = new Intent();
                                intent.putExtra("picId", key);
                                setResult(100, intent);
                                AppManager.getAppManager().finishActivity();
                            }
                        });

                    }

                    @Override
                    public void onFailure(String failReason) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                picFile.delete();
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                            }
                        });

                    }
                });
    }


    // Java文件操作 获取不带扩展名的文件名

    public String getFileNameNoEx(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                int index = filename.indexOf("-");
                return filename.substring(index + 1, dot);
            }
        }
        return filename;
    }


    @OnClick({R.id.textView_tip, R.id.take_photo_cancel, R.id.take_photo_ok, R.id.light_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.textView_tip:
                break;
            case R.id.take_photo_cancel:
                if (ivPreview.getVisibility() == View.VISIBLE) {
                    ivPreview.setVisibility(View.GONE);
                    takePhotoButton.setVisibility(View.VISIBLE);
                    takePhotoOk.setVisibility(View.GONE);
                } else {
                    AppManager.getAppManager().finishActivity();
                }
                break;
            case R.id.take_photo_ok:
                preUploadImage(file);
                break;
            case R.id.light_button:
                if (cameraView.getCameraControl().getFlashMode() == ICameraControl.FLASH_MODE_OFF) {
                    cameraView.getCameraControl().setFlashMode(ICameraControl.FLASH_MODE_TORCH);
                } else {
                    cameraView.getCameraControl().setFlashMode(ICameraControl.FLASH_MODE_OFF);
                }
                updateFlashMode();
                break;
        }
    }

    private void updateFlashMode() {
        int flashMode = cameraView.getCameraControl().getFlashMode();
        if (flashMode == ICameraControl.FLASH_MODE_TORCH) {
            lightButton.setImageResource(com.baidu.ocr.ui.R.drawable.bd_ocr_light_on);
        } else {
            lightButton.setImageResource(com.baidu.ocr.ui.R.drawable.bd_ocr_light_off);
        }
    }

}
